//
//  chooseMemberViewController.m
//  HJB
//
//  Created by jiezsoft.com on 14-10-10.
//  Copyright (c) 2014年 jiezsoft.com. All rights reserved.
//

#import "ChooseMemberViewController.h"
#import "GenerateQRCodeViewController.h"
#import "AddMemberViewController.h"
#import "MJRefresh.h"
#import "TagsCell.h"
#import "ChooseMemberCell.h"
#import "TheLoginViewController.h"
#import "MemberListModel.h"
#import "FilterView.h"
#import "MemberSendMsgViewController.h"
@interface ChooseMemberViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UISearchBarDelegate,FilterViewDelegate,AddMemberViewControllerControllerDelegate>
@property (strong, nonatomic) NSString*orderField;
@end
@implementation ChooseMemberViewController
{
    UISearchBar *search;
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSMutableArray*modelArray;
    NSMutableArray*searchBeans;
    UITableView *table;
    UIButton*screeningBtn;
    int pageNumber;
    MBProgressHUD *progressHud;
    UITextField*searchTextField;
    UIView*tableHeaderView;
    UIView*myToolBar;
    UIButton* screeningBtnImage;
    UIButton* addBtn;
    UIView*addView;
    UIView*optionsView;
    BOOL saveAccount;
    NSString* TotalCount;
   
}
@synthesize alt = alt;

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    saveAccount=YES;
}
-(void)update:(NSString *)Str{
    [self setNavigation];
    [self requestData];
    table .frame=CGRectMake(0, 64, ScreenWidth, ScreenHeight);
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    searchBeans=[[NSMutableArray alloc]init];
    [self setNavigation];
    [self requestData];
}
-(void)addoptions:(UIButton *)sender{
    AddMemberViewController *detailViewController = [[AddMemberViewController alloc] init];
    detailViewController.delegate=self;
    [self.navigationController pushViewController:detailViewController animated:YES];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [searchTextField resignFirstResponder];
    [self requestData];
    
    return YES;
    
}
-(void)requestData{
    modelArray=[[NSMutableArray alloc]init];
    
    pageNumber = 1;
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"pageIndex"];
    [param setValue:@"20" forKey:@"pageSize"];
    [param setValue:self.orderField forKey:@"orderField"];
    [param setValue:self.orderSort forKey:@"orderSort"];
    [param setValue:searchTextField.text forKey:@"searchWord"];
    [param setValue:searchBeans forKey:@"searchBeans"];
    [param setValue:@"2" forKey:@"filterType"];
    if (searchBeans .count>0) {
        [screeningBtnImage setImage:[UIImage imageNamed:@"shaixuan"] forState:UIControlStateNormal];
    }
 [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Business/Member/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                    TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];

                    UILabel*totalcount=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, 200, 40)];
                    totalcount.text=[NSString stringWithFormat:@"共有 %@ 个结果",TotalCount];
                    totalcount.font=[UIFont systemFontOfSize:14];
                    [tableHeaderView addSubview:totalcount];
                NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                for (NSDictionary *dic in mItemsArray) {
                    MemberListModel *dataModel=[MemberListModel dataModelWithDict:dic];
                    [modelArray addObject:dataModel];
                }
                [table reloadData];
            }else{
                [Global hideProgressHUDInternal:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController*vc1=[[TheLoginViewController alloc] init];
                    [self.navigationController pushViewController:vc1 animated:YES];
                }
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
}

//上拉刷新数据
- (void)addFooter
{
    
    MJRefreshFooterView* footer = [MJRefreshFooterView footer];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        
        if (TotalCount.doubleValue/20.00>=pageNumber) {
            pageNumber++;
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString* Token = [user objectForKey:@"tokenId"];
            if (Token ==nil) {
                Token=@"dd";
            }
            NSMutableDictionary *param = [NSMutableDictionary new];
            [param setValue:Token forKey:@"tokenId"];
            [param setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
            [param setValue:@"20" forKey:@"pageSize"];
            [param setValue:self.orderField forKey:@"orderField"];
            [param setValue:self.orderSort forKey:@"orderSort"];
            [param setValue:searchTextField.text forKey:@"searchWord"];
            [param setValue:searchBeans forKey:@"searchBeans"];
//            NSLog(@"====%@",param);
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            [HttpRequest requestData:@"Business/Member/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    //
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                        for (NSDictionary *dic in mItemsArray) {
                            MemberListModel *dataModel=[MemberListModel dataModelWithDict:dic];
                            [modelArray addObject:dataModel];
                        }
                        [table reloadData];
                    }else{
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                    }
                    
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:severDataDict.resultStr view:self.view];
                }
                
            }];
        }else{
            
            NSString *requestResultStr=@"没有更多数据了！";
            [Global showTextHudSub:requestResultStr view:self.view];
        }
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:3.0f];
//        NSLog(@"%@--->正在刷新", refreshView.class);
    };
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    
    
    [table reloadData];
    [refreshView endRefreshing];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [modelArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChooseMemberCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MemberListViewController"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model=modelArray[indexPath.row];
    
    return cell;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  50;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
           MemberListModel *ScreeningModel=modelArray[indexPath.row];

            [self.delegate  memberIdStr:ScreeningModel.memberId userName:ScreeningModel.userName phone:ScreeningModel.phone sex:ScreeningModel.sex consigneeName:ScreeningModel.consigneeName consigneeAddr:ScreeningModel.address consigneePhone:ScreeningModel.consigneePhone];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}
- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
-(void)setNavigation{
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    self.navigationController.navigationBarHidden=NO;
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    
    UIView* sousuoView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth*570/750, 65/2)];
    sousuoView.backgroundColor=zuiqianhuiColor;
    UIButton *screeningBtnImage1 = [[UIButton alloc] initWithFrame:CGRectMake(2, 4, 50/2, 50/2)];
    [screeningBtnImage1 setImage:[UIImage imageNamed:@"sousuo"] forState:UIControlStateNormal];
    [sousuoView addSubview:screeningBtnImage1];
    searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(screeningBtnImage1.right,1, ScreenWidth*500/750,65/2)];
    [searchTextField setBorderStyle:   UITextBorderStyleNone]; //外框类型
    searchTextField.placeholder = @"会员/手机号/姓名"; //默认显示的字
    searchTextField.font = [UIFont systemFontOfSize: 14];
    searchTextField.tag=22;
    searchTextField.returnKeyType = UIReturnKeyDone;
    searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    searchTextField.delegate = self;
    searchTextField.tintColor =tintColors;
    [sousuoView addSubview:searchTextField];
    
    self.navigationItem.titleView = sousuoView;
    
    addBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0, 60/2, 60/2)];
    [addBtn setImage:[UIImage imageNamed:@"tianjia"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addoptions:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
    self.navigationItem.rightBarButtonItem = myBtnBtn;
    
    myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"确定" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:17];
    [btnDone111 addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];
    searchTextField.inputAccessoryView = myToolBar;
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [table registerClass:[ChooseMemberCell class] forCellReuseIdentifier:@"MemberListViewController"];
    [self.view addSubview:table];
    [self addFooter];
  
        tableHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
        tableHeaderView.backgroundColor=zuiqianhuiColor;
        table.tableHeaderView=tableHeaderView;
    
    
}
-(void)BackAction:(UIButton *)sender{
    [searchTextField resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)OnTapDone{
    
    [searchTextField resignFirstResponder];
    
}


@end
